<?php

namespace Beerus\Modules\Designer\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use App\Http\Controllers\Controller;
use Doraemon\cache\User as CacheUser;
use Doraemon\cache\UserAuthStatus;
use Doraemon\model\AdmUserType;
use Doraemon\model\Designer;
use Doraemon\model\Designer\DesignerEquity;
use Doraemon\model\DesignerAuth;
use Doraemon\model\DesignerPayService;
use Doraemon\model\DesignerTeam;
use Doraemon\model\Member;
use Doraemon\service\Designer\AuthService;
use Doraemon\tools\Log;
use Illuminate\Http\Request;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Support\MessageBag;
use Encore\Admin\Widgets\Form;
use Doraemon\service\User;
use Doraemon\cache\Queue;

/**
 * 设计师机构团队管理
 *
 * @category   Module name
 * @package    PSR
 * @subpackage Documentation\API
 * @author     zhouyang  <zhouyang@haohaozhu.com>
 * @license    GPL http://www.haohaozhu.com
 * @link       http://www.haohaozhu.com
 */
class DesignerTeamController extends Controller
{
    const PAGE_SIZE = 20;

    const STATUS = [
        0 => '已解绑',
        1 => '已绑定'
    ];

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $request_data = $request->all();

        $page_size = $request->input('per_page', self::PAGE_SIZE);
        $page = $request->input('page', 1);

        $condition = [];
        if (!empty($request_data['org_uid'])) {
            $condition['org_uid'] = $request_data['org_uid'];
        }

        if (!empty($request_data['org_nick'])) {
            $uid = User::getUidByNick($request_data['org_nick']);
            $condition['org_uid'] = $uid;
        }

        if (!empty($request_data['member_uid'])) {
            $condition['member_uid'] = $request_data['member_uid'];
        }

        if (!empty($request_data['member_nick'])) {
            $uid = User::getUidByNick($request_data['member_nick']);
            $condition['member_uid'] = $uid;
        }

        $condition['ORDER'] = ['id' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];

        $lists = DesignerTeam::select('*', $condition);

        $total = 0;
        if (!empty($lists)) {
            unset($condition['ORDER']);
            unset($condition['LIMIT']);
            $total = DesignerTeam::count($condition);
            $org_ids = array_column($lists, 'org_uid');
            $member_ids = array_column($lists, 'member_uid');
            $user_ids = array_merge($org_ids, $member_ids);

            $member_info = Member::getUsers($user_ids);

            foreach ($lists as &$item) {
                $item['org_nick'] = empty($member_info[$item['org_uid']]['nick']) ?
                    '' : $member_info[$item['org_uid']]['nick'];
                $item['member_nick'] = empty($member_info[$item['member_uid']]['nick']) ?
                    '' : $member_info[$item['member_uid']]['nick'];
            }
            unset($item);
        }

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('org_uid', '机构UID')->placeholder('请输入机构uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('org_nick', '机构昵称')->placeholder('请输入机构昵称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('member_uid', '成员UID')->placeholder('请输入成员uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('member_nick', '成员昵称')->placeholder('请输入成员昵称');
                    });
                    $filter->expand();
                });

                $grid->column('org_uid', '机构UID')->width(100);
                $grid->column('org_nick', '机构昵称')->width(200);
                $grid->column('member_uid', '成员UID')->width(100);
                $grid->column('member_nick', '成员昵称')->width(200);
                $grid->column("position", '成员职位')->display(function () {
                    if (empty($this->position)) {
                        return '-';
                    }
                    return $this->position;
                })->width(180);
                $grid->column("add_time", '绑定时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->add_time);
                })->width(180);
                $grid->column("edit_time", '修改时间')->display(function () {
                    if (empty($this->edit_time)) {
                        return '-';
                    }
                    return date("Y-m-d H:i:s", $this->edit_time);
                })->width(180);

                $grid->column("status", '数据状态')->display(function () {
                    return self::STATUS[$this->status];
                })->width(80);
                $grid->column("admin_id", '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '-';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                })->width(100);
                $grid->column("remark", '备注');

                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableDelete();
                });
            }
        );

        $tab = new Tab();
        $title = '机构团队管理';
        $tab->add($title, $gridList->render());
        return $content
            ->row($tab)
            ->header($title)
            ->breadcrumb(['text' => $title]);
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $request = $request->all();

        if ($id == 0) {
            $is_create = true;
            $header = '添加成员';
        } else {
            $is_create = false;
            $header = '修改成员';
        }

        $tab = new Tab();
        $tab->add('机构/成员绑定信息', self::editAction($request, $id, $is_create));
        return $content->header($header)
            ->description(' ')
            ->breadcrumb([
                'text' => '机构团队管理',
                'url' => route('designer.team')
            ], ['text' => $header])->row($tab);
    }

    public function editAction($request, $id = 0, $is_create = false)
    {
        if ($is_create) {
            $data = [
                'status' => DesignerTeam::STATUS_NORMAL,
            ];
            $form = new Form($data);

            $form->text('org_uid', '机构UID')->setWidth(4, 2)->required('不能为空');
            $form->text('member_uid', '成员UID')->setWidth(4, 2)->required('不能为空');
        } else {
            $data = DesignerTeam::get('*', ['id' => $id]);
            $form = new Form($data);
            $form->hidden('id');
            $form->text('org_uid', '机构UID')->setWidth(4, 2)->readOnly();
            $form->text('member_uid', '成员UID')->setWidth(4, 2)->readOnly();
        }

        $form->text('position', '成员职位')->setWidth(4, 2);
        $form->select('status', '绑定状态')->default(DesignerTeam::STATUS_NORMAL)
            ->setWidth(4, 2)->options(self::STATUS);
        $form->textarea('remark', '备注')->setWidth(4, 2)->required('修改必须加备注|||');

        $form->action('/admin/Designer/team/save');

        return $form->render();
    }

    public function editSubmit(Request $request)
    {
        $request = $request->all();

        if (empty(trim($request['remark']))) {
            $error = new MessageBag([
                'title' => '必须填写备注'
            ]);

            return back()->withInput()->with(compact('error'));
        }

        $data = [
            'org_uid' => $request['org_uid'],
            'member_uid' => $request['member_uid'],
            'position' => $request['position'],
            'status' => $request['status'],
            'admin_id' => Admin::user()->id,
            'remark' => $request['remark']
        ];

        if (isset($request['id'])) {
            $data['edit_time'] = time();
            if ($data['status'] == 0) {
                try {
                    $rs = $this->unfounded($data, $request['id']);
                } catch (\Exception $e) {
                    $rs = false;
                }
            } else {
                // 更新团队记录
                $rs = DesignerTeam::update($data, [
                    'id' => $request['id']
                ]);
            }
        } else {
            $data['add_time'] = time();
            $rs = DesignerTeam::create($data);
        }

        if ($rs) {
            if (isset($request['id'])) {
                $title = '修改成功';
            } else {
                $title = '添加成功';
            }

            $success = new MessageBag([
                'title' => $title
            ]);

            return redirect('/admin/Designer/team')->with(compact('success'));
        } else {
            if (isset($request['id'])) {
                $title = '修改失败';
            } else {
                $title = '添加失败';
            }

            $error = new MessageBag([
                'title' => $title
            ]);

            return back()->withInput()->with(compact('error'));
        }
    }

    /**
     * @Notes: 解绑操作需要同步修改子账号认证
     * @param $params
     * @param $id
     * @return bool
     * @throws \Exception
     * @author: weiyizheng
     * @Time: 2022/3/15
     */
    public function unfounded($params, $id)
    {
        $uid = $params['member_uid'];
        $org_uid = $params['org_uid'];
        // 子账号设计师信息
        $auth_info = DesignerAuth::getByUId($uid);
        if ((int)$auth_info['designer_type'] != DesignerAuth::DESIGNER_TYPE_COMPANY_BYPASS) {
            throw new \Exception("账号信息有误");
        }

        $res = DesignerPayService::getNormalService($uid);
        if (!empty($res)) {
            DesignerPayService::update([
                'end_time' => time(),
                'status' => DesignerPayService::STATUS_END
            ], [
                'id' => $res['id']
            ])->rowCount();
        }

        // 将设计师账号变更为未认证设计师
        AuthService::unAuth($uid);

        // 更新到期时间为解绑时间
        $update_data = [
            'expire_time' => time(),
            'house_article_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
            'identity_info_audit_status' => DesignerAuth::STATUS_AUDIT_SUPPLEMENT,
        ];
        DesignerAuth::update($update_data, ['uid' => $uid])->rowCount();


        // 更新团队记录
        DesignerTeam::update($params, [
            'id' => $id
        ])->rowCount();


        $org_user_info = User::getBasicUserInfo($org_uid);
        $org_nick = empty($org_user_info) ? '' : $org_user_info['nick'];
        // 发送下行消息
        $message_data = [
            'msgCode' => 0,
            'to_uid' => $uid,
            'msgParams' => [
                'from_uid' => User::DEFAULT_HAOHAOZHU_UID,
                'title' => '',
                'detail' => "你好，你的账号和机构账号「{$org_nick}」的绑定关系被解除，身份变更为未认证设计师，如果有问题，请及时和我们反馈。",
            ]
        ];
        Queue::insertQueue('queue/Sysmsg/Send', $message_data, Queue::QUEUE_DORAEMON);

        Log::info("designer_team unfounded log", $params);
        return true;
    }
}
